package ControllerCSV

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"ustcLab/conf"
	"ustcLab/server/service/ServiceCSV"
	"ustcLab/server/service/ServiceGraph"
)

// HandlerBatchUpload 批量上传
func HandlerBatchUpload(ctx *gin.Context) {

}

// HandlerCSVUpload excel表格单个文件上传
func HandlerCSVUpload(ctx *gin.Context) {
	recFile, err := ctx.FormFile("file")
	if err != nil {
		ctx.String(400, "file type error!")
		return
	}

	if recFile.Size > conf.UploadFileMaxSize {
		ctx.String(400, fmt.Sprintf(
			"file size more than uploadFileMaxSize(%d)", conf.UploadFileMaxSize))
		return
	}
	tripleData, err := ServiceCSV.ProcessTableData(recFile)
	if err != nil {
		ctx.String(400, "processCSV failed! err: %s", err.Error())
		log.Printf("processCSV failed! err: %s", err.Error())
		return
	}
	for _, item := range tripleData {
		if item == nil {
			continue
		}
		log.Printf("[Level DEBUG][HandlerCSVUpload] A[%s] --%s--> B[%s]\n",
			item.Substance, item.Relation, item.Object)
		res, err := ServiceGraph.InsertItem(item)
		if err != nil {
			log.Println("[HandlerCSVUpload] write tripleData err: ", err.Error())
			ctx.String(400, "[HandlerCSVUpload] write tripleData err:", err.Error())
			return
		}
		log.Println("[HandlerCSVUpload] write tripleData success. return: ", res)
	}

	ctx.String(200, "csv数据导入成功")
	log.Println("csv数据导入成功")
}
